import { request } from "../../request/index";
import { requestPayment, showToast } from "../../utils/asyncWX";

Page({
  data:{
    address:{},
    cart:[],
    totalNum:0,
    totalPrice:0
  },

  onShow(){
    // 1 获取本地缓存数据
    const address=wx.getStorageSync('address');
    let cart=wx.getStorageSync('cart')||[];
    // 过滤后购物车数组
    cart=cart.filter(v => v.checked);
    this.setData({address});

    // 总价格和数量
    let totalNum=0;
    let totalPrice=0;
    cart.forEach(v => {
      if(v.checked){
        // 如果被选中 总数+num 总价+num*price
        totalNum += v.num;
        totalPrice += v.num * v.goods_price;
      }
    });
    // 赋值给data
    this.setData({
      cart,
      totalNum,
      totalPrice,
      address
    });
  },

  // 支付
  async handleOrderPay(){
    try {
      // 判断缓存中是否有token
      const token=wx.getStorageSync('token');
      if(!token){
        wx.navigateTo({
          url: '/pages/auth/index',
        });
        return;
      }
      // 获取token后
      // 创建订单
      // 1 准备请求头
      // const header={Authorization: token};
      // 2 准备请求体参数
      const oeder_price=this.data.totalPrice;
      const consignee_addr=this.data.all;
      const cart=this.data.cart;
      let goods=[];
      cart.forEach(v=>goods.push({
        goods_id:v.goods_id,
        goods_number:v.num,
        goods_price:v.goods_price,
      }));
      const orderPatams={oeder_price,consignee_addr,goods}
      // 4 发送订单请求，获取订单号
      const {order_number}=await request({url:"/my/orders/create",method:"POST",data:orderPatams});
      // 5 发起预支付接口
      const {pay}=await request({url:"/my/orders/req_unifiedorder",method:"POST",data:{order_number}});
      // 6 发起微信支付
      await requestPayment(pay);
      // 7 查询后台订单状态
      const res=await request({url:"/my/orders/chkOrder",method:"POST",data:{order_number}});
      await showToast({title:"支付成功"});
      // 8 手动删除缓存中已支付的商品
      let newCart=getStorageSync('cart');
      newCart=cart.filter(v=>!v.checked);
      wx.setStorageSync('cart', newCart);
      // 9 成功后跳转到订单页面
      await wx.navigateTo({
        url: '/pages/order.index',
      });
        
    } catch (error) {
      await showToast({title:"支付失败"});
      console.log(error);
    }
  }

})